package swu.cx.finalproject

import android.content.Context


class SharedPreferenceUtil private constructor() {
    private val FILE_NAME = "password"
    private val KEY = "passwordKey"
    val USERNAME = "UserInformation"
    val PASSWORD = "PasswordInformation"
    companion object{
        private var mContext: Context? = null
        private var instance: SharedPreferenceUtil? = null

        fun getInstance(context: Context): SharedPreferenceUtil{
            mContext = context

            if(instance == null){
                synchronized(this){
                    instance = SharedPreferenceUtil()
                }
            }

            return instance!!
        }
    }

    fun savePassword(pwd: String){
        //获取preference对象
        val sharedPreference = mContext?.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE)
        //获取edit对象 -> 写数据
        val edit = sharedPreference?.edit()
        //写入数据
        edit?.putString(KEY,pwd)
        //提交
        edit?.apply()
    }

    fun getPassword(): String?{
        //获取preference对象
        val sharedPreference = mContext?.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE)
        return sharedPreference?.getString(KEY,null)
    }
    fun SaveUserInfo(UserInfo: String) {
        //获取Preferences对象
        mContext?.getSharedPreferences(USERNAME, Context.MODE_PRIVATE).also {
            //写入数据
            it?.edit()?.putString(USERNAME, UserInfo)?.apply()
        }
    }
    fun SavePasswordInfo(PasswordInfo: String) {
        mContext?.getSharedPreferences(PASSWORD, Context.MODE_PRIVATE).also {
            it?.edit()?.putString(PASSWORD, PasswordInfo)?.apply()
        }
    }

    fun GetUserInfo(): String? {
        //获取preference对象
        mContext?.getSharedPreferences(USERNAME, Context.MODE_PRIVATE).also {
            return it?.getString(USERNAME,null)
        }
    }

    fun GetPasswordInfo(): String? {
        mContext?.getSharedPreferences(PASSWORD, Context.MODE_PRIVATE).also {
            return it?.getString(PASSWORD, null)
        }
    }

}